package com.voc.im.model;

import com.voc.im.bean.UserRoom;
import com.voc.im.common.Constants;
import io.datafx.controller.injection.scopes.ApplicationScoped;
import javafx.beans.property.*;
import javafx.collections.FXCollections;

import java.util.List;

@ApplicationScoped
public class UserRoomModel {

    private ListProperty<UserRoom> userListProperty;

    private ListProperty<UserRoom> roomListProperty;

    private IntegerProperty selectedUserIndex;

    private IntegerProperty selectedRoomIndex;

    private ListProperty<UserRoom> userListProperty() {
        if (userListProperty == null) {
            userListProperty = new SimpleListProperty<>(FXCollections.observableArrayList());
        }
        return userListProperty;
    }

    public ListProperty<UserRoom> getUserListProperty() {
        return userListProperty();
    }

    private ListProperty<UserRoom> roomListProperty() {
        if (roomListProperty == null) {
            roomListProperty = new SimpleListProperty<>(FXCollections.observableArrayList());
        }
        return roomListProperty;
    }

    public ListProperty<UserRoom> getRoomListProperty() {
        return roomListProperty();
    }

    public void addUserProperty(List<UserRoom> userRooms) {
        this.getUserListProperty().addAll(userRooms);
    }

    public void addRoomProperty(List<UserRoom> userRooms) {
        this.getRoomListProperty().addAll(userRooms);
    }

    public void addProperty(UserRoom userRoom) {
        int position = -1;
        for (int i = 0; i < getUserListProperty().size(); i++) {
            UserRoom user = getUserListProperty().get(i);
            if (userRoom.getId() == user.getId()) {
                position = i;
                break;
            }
        }
        if (position == -1) {
            if (userRoom.getType() == Constants.USER_ROOM_1) {
                this.getUserListProperty().add(userRoom);
            } else if (userRoom.getType() == Constants.USER_ROOM_2) {
                this.getRoomListProperty().add(userRoom);
            }
        } else {
            if (userRoom.getType() == Constants.USER_ROOM_1) {
                this.getUserListProperty().set(position, userRoom);
            } else if (userRoom.getType() == Constants.USER_ROOM_2) {
                this.getRoomListProperty().set(position, userRoom);
            }
        }
    }

    private IntegerProperty selectedUserIndex() {
        if (selectedUserIndex == null) {
            selectedUserIndex = new SimpleIntegerProperty();
        }
        return selectedUserIndex;
    }

    public IntegerProperty getSelectedUserIndex() {
        return selectedUserIndex();
    }

    private IntegerProperty selectedRoomIndex() {
        if (selectedRoomIndex == null) {
            selectedRoomIndex = new SimpleIntegerProperty();
        }
        return selectedRoomIndex;
    }

    public IntegerProperty getSelectedRoomIndex() {
        return selectedRoomIndex();
    }
}
